package com.zx.sa.config;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.ollama.OllamaEmbeddingModel;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@Configuration
public class AiConfig {

    @Primary
    @Bean(name = "openAiChatClient")
    public ChatClient openAiChatClient(@Qualifier("openAiChatModel") ChatModel chatModel) {
        return this.builderChatClient(chatModel);
    }

    @Primary
    @Bean(name = "custOpenAiEmbeddingModel")
    public EmbeddingModel openAiEmbeddingModel(@Qualifier("openAiEmbeddingModel") EmbeddingModel embeddingModel) {
        return embeddingModel;
    }


    @Bean(name = "ollamaAiChatClient")
    public ChatClient ollamaAiChatClient(@Qualifier("ollamaChatModel") ChatModel chatModel) {
        return this.builderChatClient(chatModel);
    }

    @Bean(name = "custOllamaAiEmbeddingModel")
    public EmbeddingModel custOllamaAiEmbeddingModel(
            @Qualifier("ollamaEmbeddingModel") OllamaEmbeddingModel embeddingModel) {
        return embeddingModel;
    }

    @Bean(name = "zhiPuAiChatClient")
    public ChatClient zhiPuAiChatClient(@Qualifier("zhiPuAiChatModel") ChatModel chatModel) {
        return this.builderChatClient(chatModel);
    }

    @Bean(name = "custZhiPuAiEmbeddingModel")
    public EmbeddingModel zhiPuAiEmbeddingModel(@Qualifier("zhiPuAiEmbeddingModel") EmbeddingModel embeddingModel) {
        return embeddingModel;
    }


    @Bean(name = "dashscopeChatClient")
    public ChatClient dashscopeChatClient(@Qualifier("dashscopeChatModel") ChatModel chatModel) {
        return this.builderChatClient(chatModel);
    }

    private ChatClient builderChatClient(ChatModel chatModel) {
        return ChatClient.builder(chatModel)
                .defaultSystem("你是张雪的个人生活管家，回答各种问题！")
                // 实现 Chat Memory 的 Advisor
                // 在使用 Chat Memory 时，需要指定对话 ID，以便 Spring AI 处理上下文。
                .defaultAdvisors(new MessageChatMemoryAdvisor(new InMemoryChatMemory()))
                // 实现 Logger 的 Advisor
                .defaultAdvisors(new SimpleLoggerAdvisor())
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(DashScopeChatOptions.builder().withTopP(0.7).build())
                .build();
    }

}
